package top.lixunda.commerce.gateway.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Map;

/**
 * 打印来到网关的请求
 *
 * @author LiXunda
 * @version time:2019/8/30 20:21
 */
@Slf4j
public class AccessLogWebFilter implements WebFilter, Ordered {

    @SuppressWarnings("NullableProblems")
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().pathWithinApplication().value();
        HttpMethod method = request.getMethod();
        // 获取路由的目标URI
        URI targetUri = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        Map<String, String> headers = request.getHeaders().toSingleValueMap();
        Map<String, HttpCookie> cookies = request.getCookies().toSingleValueMap();
        return chain.filter(exchange.mutate().build()).then(Mono.fromRunnable(() -> {
            ServerHttpResponse response = exchange.getResponse();
            Map<String, String> responseHeaders = response.getHeaders().toSingleValueMap();
            HttpStatus statusCode = response.getStatusCode();
            log.info("");
            log.info("gateway\t\t请求路径:{}   客户端远程IP地址:{}   请求方法:{}   目标URI:{}   响应码:{}",
                    path, remoteAddress, method, targetUri, statusCode);
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                log.info("FirstHeaders\t\tkey:{} name:{} value:{}", entry.getKey(), entry.getValue());
            }
            for (Map.Entry<String, HttpCookie> entry : cookies.entrySet()) {
                    log.info("FirstCookies   key:{} name:{} value:{}", entry.getKey(), entry.getValue().getName(), entry.getValue().getValue());
            }

            for (Map.Entry<String, String> entry : responseHeaders.entrySet()) {
                log.info("FirstResponseHeaders   key:{} name:{} value:{}", entry.getKey(), entry.getValue());
            }
        }));
    }

    @Override
    public int getOrder() {
        return -10000;
    }
}
